<template>
  <div>
    <el-button type="danger" :loading="syncLoading" size="mini" @click="sync('1')">数据同步</el-button>
    <el-button type="primary" :loading="syncLoading" size="mini" @click="refresh()">刷新</el-button>
    <!--<el-button type="primary" size="mini" class="addBtn" @click="openAddDrawer()">添加</el-button>-->
    <el-row :gutter="20">
      <el-col :span="16">
        <el-divider content-position="left">分类列表</el-divider>
        <el-table
        v-loading="loading"
        :data="typeList"
        id="datatable"
        border
        style="width: 100%"
        element-loading-text="数据加载中"
        element-loading-spinner="el-icon-loading"
      >
        <el-table-column type="expand"  fixed="left">
          <template slot-scope="scope">
            <el-tag type="danger" v-if="scope.row.blogList.length === 0" style="margin-right: 10px">暂无博客</el-tag>
            <el-tag v-for="(item,index) in scope.row.blogList"
                    v-loading="tagLoading"
                    closable
                    :disable-transitions="false"
                    @click="handleBlogInfo(item)"
                    @close="handleClose(scope.row.typeId,item,scope.row)"
                    :key="index"
                    :color="item.tagColor"
                    style="margin-right: 10px;margin-bottom: 10px">
              {{item.blogTitle}}
            </el-tag>
            <el-popover
              placement="right"
              width="400"
              height="400"
              trigger="click">
              <el-table :data="deBlogs" v-loading="tableloading">
                <el-table-column width="250" show-overflow-tooltip property="blogTitle" label="标题"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope2">
                    <el-button size="mini" type="primary" @click="handleCommand(scope2.row.blogId,scope.row.typeId,scope2.row,scope.row)">选择</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-button type="primary" slot="reference" size="mini" @click="addTypes(scope.row.blogList)">添加+</el-button>
            </el-popover>
            <!--<el-dropdown @command="handleCommand" trigger="click" @visible-change="handleVisible">
              <span class="el-dropdown-link">
                <el-button type="primary" :loading="syncLoading" size="mini" @click="addTypes(scope.row.blogList)">添加+</el-button>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="item.blogId" v-for="(item,index) in deBlogs">{{item.blogTitle}}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>-->

          </template>
        </el-table-column>
        <el-table-column
          prop="typeId"
          label="分类id"
        />
        <el-table-column
          prop="typeName"
          label="分类名"
        />
        <el-table-column
          prop="typeBlogCount"
          label="博客数量"
        />
        <el-table-column
          label="是否启用"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.enable===1" type="success">启用</el-tag>
            <el-tag v-else type="danger">未启用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-dropdown trigger="hover">
              <el-button size="mini" type="primary">
                操作<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <el-button size="mini" type="primary" @click="handlerEdit(scope.row.typeId)">编辑</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="isAdmin">
                  <el-button size="mini" type="danger" @click="handlerDelete(scope.row.typeId)">删除</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="isAdmin">
                  <el-button size="mini" type="success" @click="handlerEnable(scope.row.typeId)">启用</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="isAdmin">
                  <el-button size="mini" type="warning" @click="handlerDisable(scope.row.typeId)">弃用</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>

        </el-table-column>
      </el-table>
      </el-col>
      <el-col :span="8">
        <el-divider content-position="left">分类添加</el-divider>
        <el-form ref="ruleForm" :model="addType" label-width="100px">
          <el-form-item label="分类名称" prop="typeName">
            <el-input v-model="addType.typeName" />
          </el-form-item>
          <el-form-item v-if="isAdmin" label="关联博客" prop="blogList">
            <el-select v-model="blogList" filterable multiple placeholder="请选择标签" style="width: 100%" @focus="getAllBlogsUndeletedAndEnabled()">
              <el-option
                v-for="item in blogInfos"
                :key="item.blogId+'-'+item.blogType"
                :label="item.blogTitle"
                :value="item.blogId+'-'+item.blogType"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="提交" label-width="100px">
            <el-button :loading="saveLoading" type="primary" @click="submitForm()">添加</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-drawer
      title="添加分类"
      :visible.sync="drawer"
    >
      <type-add @getTypeList="getTypeList" @closeAddDrawer="closeAddDrawer" />
    </el-drawer>
    <el-dialog
      title="更新分类"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <type-update :type="type" @getTypeList="getTypeList" @closeUpdateDialog="closeUpdateDialog" />
    </el-dialog>
  </div>
</template>

<script>
import typeApi from '@/api/type'
import typeAdd from './type-add'
import typeUpdate from './type-update'
import {contentSync} from '@/utils'
import blogApi from "../../../api/blog";
import _ from 'lodash'
export default {
  name: 'TypeList',
  components: {
    typeAdd,
    typeUpdate
  },
  data() {
    return {
      // 数据列表
      typeList: [],
      drawer: false,
      dialogVisible: false,
      type: {},
      loading: true,
      isAdmin: false,
      addType:{},
      saveLoading:false,
      syncLoading:false,
      blogInfos:[],
      blogList:[],
      deBlogs:[],
      czvisible:false,
      tableloading:false,
      tagLoading:false
    }
  },
  created() {
    this.getTypeList()
    const username = this.$store.getters.username
    if (username === 'admin') {
      this.isAdmin = true
    }
  },
  methods: {
    // true is display | false is hide
    handleVisible(flag){
      if(!flag){
        this.deBlogs = []
      }
    },
    // 关闭标签
    handleClose(typeId,item,row){
      if(typeId === 0){
        this.$message.error('不能删除默认分类');
        return;
      }
      let ts = this.typeList.find(e=>e.typeId===0).blogList.filter(e=>_.isEqual(e,item));
      if(ts && ts.length && ts.length >0){
        this.$message.error('默认分类中存在改标签，所以不能关闭该标签')
        return;
      }
      this.tagLoading = true
      typeApi.deleteTypeBlog(typeId,item.blogId).then(res=>{
        if(res.code === 200){
          // 删除掉现在的
          row.blogList.splice(row.blogList.findIndex(e=>_.isEqual(item,e)),1)
          // 当前这一行-1
          row.typeBlogCount = row.typeBlogCount - 1
          // 添加默认的
          let t = this.typeList.find(e=>e.typeId === 0);
          if(t){
            t.typeBlogCount = t.typeBlogCount+1
            t.blogList.push(item)
          }else{
            console.error('------默认分类不存在------')
          }
          this.tagLoading = false
        }else{
          this.tagLoading = false
        }
      }).catch(e=>{
        this.tagLoading = false
      })
    },
    deleteTypeBlog(){

    },
    handleCommand(blogId,blogType,blogInfo,sourceBlog){
      this.tableloading = true
      let ts = sourceBlog.blogList.filter(e=>e.blogId === blogId);
      if(ts.length && ts.length>0){
        this.$message.error('该类型已经被添加不能再次被添加')
        this.tableloading = false
        document.getElementById('datatable').click()
        return;
      }
      typeApi.saveTypeBlog(blogType,blogId).then(res=>{
        if(res.code === 200){
          let number = this.deBlogs.findIndex(e=>_.isEqual(e,blogInfo));
          this.deBlogs.splice(number,1)
          sourceBlog.blogList.push(blogInfo)
          sourceBlog.typeBlogCount =  sourceBlog.typeBlogCount + 1;
          if(res.data || res.data === 0){
            let t = this.typeList.find(e=>e.typeId === res.data)
            t.typeBlogCount = t.typeBlogCount - 1
            let number1 = t.blogList.findIndex(e=>e.blogType === res.data)
            t.blogList.splice(number1,1)
          }
          this.tableloading = false
          // 关闭弹窗 垃圾饿了么 提供的方法失效 逼我不得不采用这种方法
          document.getElementById('datatable').click()
        }
      }).catch(e=>{
        this.tableloading = false
      })
    },
    addTypes(blogList){
      //console.log(blogList)
      this.deBlogs = []
      this.czvisible = !this.czvisible
      console.log(this.czvisible )
      blogApi.getAllBlogsUndeletedAndEnabled().then(res=>{
        if(res.code === 200){
          let data = res.data;
          data.forEach(e=>{
            let flag = false
            blogList.forEach(e2=>{
              if(_.isEqual(e,e2)){
                flag = true
              }
            })
            if(!flag){
              this.deBlogs.push(e)
            }
          })
          console.log(this.deBlogs);
        }
      })
    },
    getAllBlogsUndeletedAndEnabled(){
      blogApi.getAllBlogsUndeletedAndEnabled().then(res=>{
        if(res.code === 200){
          this.blogInfos = res.data;
        }
      })
    },
    async refresh(){
      this.loading=true
      this.syncLoading = true
      this.getTypeList()
    },
    sync(type) {
      this.$confirm('此操作为数据同步, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        tag: 'warning'
      }).then(() => {
        this.loading = true
        this.syncLoading = true
        // 内容同步
        contentSync(type).then(res=>{
          if(res.code === 200){
            this.$message.success(res.data);
            this.syncLoading = false
            this.getTypeList()
          }else{
            this.$message.error('同步失败')
            this.loading = false
            this.syncLoading = false
          }
        }).catch(e=>{
          this.syncLoading = false
          this.loading = false
          this.$message.error('同步失败')
        })
      })
    },
    getTypeList() {
      typeApi.listBack().then(res => {
        this.typeList = res.data
        this.loading = false
        this.syncLoading =false
        this.$store.commit('typeList/SET_TYPELIST',this.typeList)
      })
    },
    submitForm() {
      this.saveLoading = true
      let temp = []
      this.blogList.forEach(e=>{
        let split = e.split('-');
        temp.push({blogId: split[0],blogType:split[1]})
      })
      this.addType.blogList =temp
      console.log('this.blogList',this.addType.blogList)
      typeApi.save(this.addType).then(async res => {
        if (res.code === 200) {
          this.$message.success(res.msg)
          this.addType={}
          this.blogList = []
          this.getTypeList()
          this.saveLoading = false
        }else{
          this.saveLoading = false
        }
      }).catch(e=>{
        this.saveLoading = false
      })
    },
    handlerEdit(id) {
      typeApi.get(id).then(res => {
        if (res.code === 200) {
          this.type = res.data
        }
      })
      this.openUpdateDialog()
    },
    // 跳到跟新博客界面
    handleBlogInfo(item){
      this.$nextTick(()=>{
        this.$router.push(`/Article/blogUpdate/${item.blogId}`)
      })
    },
    handlerDelete(id) {
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        typeApi.deleteById(id).then(res => {
          if (res.code === 200) {
            this.$message.success(res.msg)
          } else {
            this.loading = false
          }
          this.getTypeList()
        }).catch(e => {
          this.loading = false
        })
      })
    },
    handlerEnable(id) {
      this.$confirm('此操作将启用该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        typeApi.enableById(id).then(res => {
          this.$message.success(res.msg)
          this.getTypeList()
          this.$store.commit('typeList/SET_TYPELIST', res.data)
        })
      })
    },
    handlerDisable(id) {
      this.$confirm('此操作将弃用该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        typeApi.disableById(id).then(res => {
          this.$message.success(res.msg)
          this.getTypeList()
          this.$store.commit('typeList/SET_TYPELIST', res.data)
        })
      })
    },
    openAddDrawer() {
      this.drawer = true
    },
    closeAddDrawer() {
      this.drawer = false
    },
    openUpdateDialog() {
      this.dialogVisible = true
    },
    closeUpdateDialog() {
      this.dialogVisible = false
    }
  }
}
</script>

